package com.xvproject


import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.app.ActivityManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.view.WindowManager
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.HJNativePlugin
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import android.provider.Settings


import java.util.*

class MainActivity : FlutterActivity() {
    private final var uri = "com.world/"

    //方法调用传递
    private lateinit var methodChannel: MethodChannel

    //数据监听传递
    private lateinit var eventChannel: EventChannel


    //数据传递
    private lateinit var basicMessageChannel: BasicMessageChannel<Any>


    //DNS策略

    //这个跟flutter的通道名称保持一直
    private val CHANNEL = "samples.flutter.io/requestApi"

    //定义flutter端调用Android原生方法的channelMethod
    private val channelMethod = "requestApi"

    //flutter对Android端的传参
    private val hostArgument = "host"
    private val pathArgument = "path"
    private val methodArgument = "method"
    private val queryParametersArgument = "queryParameters"
    private val headersArgument = "headers"
    private val extraArgument = "extra"
    private val parametersArgument = "parameters"
    private val bodyParametersArgumentsKey = "bodyParameters"
    private val dnsIpArgument = "dnsIp"

    private val changeIcon = "changeIcon"
    private val iconIndex = "iconIndex"

//    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
//        super.onCreate(savedInstanceState, persistentState)
//        try {
//            val fileClass = Class.forName("android.os.HJFileUtils");
//            val setPerMethod: Method = fileClass.getDeclaredMethod("setPermissions", String::class.java, Int::class.java, Int::class.java, Int::class.java)
//setPerMethod.isAccessible = true;
//            var result = setPerMethod.invoke(null, "storage/emulated/0/.pf_id.txt", 511, -1, -1) as Int
//            print("lass = Class.forName(\"android.os.HJFileUtils\"); \${result}")
//        } catch (_: Exception) {
//
//            print("lass = Class.forName(\"android.os.HJFileUtils\"); \${_}")
//
//
//        }
//    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        HJNativePlugin.registerWith(this, flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            CHANNEL
        ).setMethodCallHandler { methodCall, result ->
            //这里是判断是不是调getIP方法，因为所有的方法都走这里
            if (methodCall.method.equals(channelMethod)) {
                var path = ""
                var params = HashMap<String, Object>()
                var headersParams = HashMap<String, Object>()
                var bodyParams = HashMap<String, Object>()
                if (methodCall.hasArgument(hostArgument) && methodCall.hasArgument(pathArgument) && methodCall.hasArgument(
                        queryParametersArgument
                    )
                ) {
                    try {
                        //取出从flutter端传递的host参数
                        val hostArgument: String? = methodCall.argument(hostArgument)
                        val pathArgument: String? = methodCall.argument(pathArgument)
                        val methodArgument: String? = methodCall.argument(methodArgument)
                        val queryParametersArgument: HashMap<String, Object>? =
                            methodCall.argument(queryParametersArgument)
                        var headersArgument: HashMap<String, Object>? =
                            methodCall.argument(headersArgument)
                        var extraArgument: HashMap<String, Object>? =
                            methodCall.argument(extraArgument)
                        var parametersArgument: HashMap<String, Object>? =
                            methodCall.argument(parametersArgument)
                        var bodyParametersArgument: HashMap<String, Object>? =
                            methodCall.argument(bodyParametersArgumentsKey)
                        var dnsValue: String? = methodCall.argument(dnsIpArgument)

                        if (queryParametersArgument != null) {
                            params = queryParametersArgument
                        }
                        if (pathArgument != null) {
                            path = pathArgument
                        }
                        if (headersArgument != null) {
                            headersParams = headersArgument
                        }
                        if (hostArgument != null) {
                            XVRequestManager.HOST = hostArgument
                        }
                        if (bodyParametersArgument != null) {
                            bodyParams = bodyParametersArgument
                        }
                        GlobalScope.launch(CoroutineName("网络请求")) {
                            var value = ""
                            when (methodArgument) {
                                "POST" -> {
                                    value = hostArgument?.let {
                                        XVRequestManager.getInstance(this@MainActivity, dnsValue)
                                            ?.requestSyn(
                                                path,
                                                XVRequestManager.TYPE_POST_JSON,
                                                bodyParams,
                                                headersParams
                                            )
                                    }.toString()
                                }

                                "GET" -> {
                                    value = hostArgument?.let {
                                        XVRequestManager.getInstance(this@MainActivity, dnsValue)
                                            ?.requestSyn(
                                                path,
                                                XVRequestManager.TYPE_GET, params, headersParams
                                            )
                                    }.toString()
                                }
                            }
                            runOnUiThread {
                                result.success(value)
                            }
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            } else if (methodCall.method.equals("getUUID")) {
                result.success(getOldId(this))
            } else if (methodCall.method.equals("setSystemBrightness")) {
                //call.argument<Double>("brightness")
            } else if (methodCall.method.equals("setAppcationIcon")) {
                result.success(true)
            } else if (methodCall.method.equals("getVersionName")) {
                result.success(getVersionName(this).toString());
            } else if (methodCall.method.equals("installApkFile")) {
//                var filePath = call.argument<String>("filePath")
//                installApkFile(this, filePath.toString())
            } else if (methodCall.method.equals("getSystemBrightness")) {
                result.success(getBrightness().toDouble())
            } else if (methodCall.method.equals("resetBrightness")) {
                result.success(getBrightness().toDouble())
                setBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE)
                result.success(true)
            } else if (methodCall.method.equals("changeShortcut")) {
                val iconName: String? = methodCall.argument("actionName")
                changeShortcut(iconName);
            } else if (methodCall.method.equals(changeIcon)) {
                //取出从flutter端传递的host参数
                val iconPosition: Int? = methodCall.argument(iconIndex)
                when (iconPosition) {

                    0 -> {
                        changeLogo("com.xvproject.lld")
                    }

                    1 -> {
                        changeLogo("com.xvproject.aiyinyue")
                    }

                    2 -> {
                        changeLogo("com.xvproject.aiyuedu")
                    }

                    3 -> {
                        changeLogo("com.xvproject.alipay")
                    }

                    4 -> {
                        changeLogo("com.xvproject.bilibili")
                    }

                    5 -> {
                        changeLogo("com.xvproject.binggandazhuozhan")
                    }

                    6 -> {
                        changeLogo("com.xvproject.meisijiejian")
                    }

                    7 -> {
                        changeLogo("com.xvproject.myworld")
                    }

                    8 -> {
                        changeLogo("com.xvproject.shenxuanzhizhan")
                    }

                    9 -> {
                        changeLogo("com.xvproject.shuixinwuxian")
                    }

                    10 -> {
                        changeLogo("com.xvproject.texuanxiaoshuo")
                    }

                    11 -> {
                        changeLogo("com.xvproject.tiantianmajiang")
                    }

                    12 -> {
                        changeLogo("com.xvproject.tuyou")
                    }

                    13 -> {
                        changeLogo("com.xvproject.weichat")
                    }

                    14 -> {
                        changeLogo("com.xvproject.wendao")
                    }

                    15 -> {
                        changeLogo("com.xvproject.yinyutusujiao")
                    }
                    //清明
                    16 -> {
                        changeLogo("com.xvproject.icon_16")
                    }
                    //端午
                    17 -> {
                        changeLogo("com.xvproject.icon_17")
                    }
                    //劳动
                    18 -> {
                        changeLogo("com.xvproject.icon_18")
                    }

                }
            }
        }
    }

    fun changeLogo(name: String) {
        val pm = packageManager
        pm.setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP
        )
        pm.setComponentEnabledSetting(
            ComponentName(this, name),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP
        )
        reStartApp(pm)
    }


    companion object {

        @TargetApi(Build.VERSION_CODES.CUPCAKE)
        public fun getOldId(ctx: Context): String {
            //从sharedPreferences获取
            val sp = ctx.getSharedPreferences("uuidstore", Activity.MODE_PRIVATE)
            val key = "uuid"
            val storedUUID = sp.getString(key, null)
            if (storedUUID != null) {
                return storedUUID
            }

            //获取唯一标示
            val androidID =
                Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.ANDROID_ID)


            val id = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                androidID + Build.SERIAL
            } else {
                androidID + Build.SERIAL
            }

            try {
                val md5 = toMD5(id)

                //存储到sp
                val editor = sp.edit()
                editor.putString(key, md5)
                editor.commit()

                return md5
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
                return id
            }
        }

        public fun toMD5(text: String): String {
            //获取摘要器 MessageDigest
            val messageDigest = MessageDigest.getInstance("MD5")
            //通过摘要器对字符串的二进制字节数组进行hash计算
            val digest = messageDigest.digest(text.toByteArray())

            val sb = StringBuilder()
            for (i in digest.indices) {
                //循环每个字符 将计算结果转化为正整数;
                val digestInt = digest[i].toInt() and 0xff
                //将10进制转化为较短的16进制
                val hexString = Integer.toHexString(digestInt.toInt())
                //转化结果如果是个位数会省略0,因此判断并补0
                if (hexString.length < 2) {
                    sb.append(0)
                }
                //将循环结果添加到缓冲区
                sb.append(hexString)
            }
            //返回整个结果
            return sb.toString()
        }
    }

    private fun setBrightness(brightness: Float) {
        val lp = window.attributes
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            lp.screenBrightness = brightness
        }
        window.attributes = lp
    }

    private fun getBrightness(): Float {
        val lp = window.attributes
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            lp.screenBrightness
        } else {

            TODO("VERSION.SDK_INT < CUPCAKE")
        }
    }

    private fun installApkFile(mContext: Activity, filePath: String) {
        XVHJInstallAppUtil.installApkFile(mContext, filePath);
    }

    private fun getVersionName(mContext: Activity): String {
        return XVHJInstallAppUtil.getVersionName(mContext);
    }

    private fun changeShortcut(actionName: String?) {
        if (actionName.isNullOrEmpty()) return
        val pm = packageManager

        pm.setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP
        )
        pm.setComponentEnabledSetting(
            ComponentName(this, actionName),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP
        )

        reStartApp(pm)
    }

    @SuppressLint("ServiceCast")
    fun reStartApp(pm: PackageManager) {
        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        intent.addCategory(Intent.CATEGORY_DEFAULT)
        val resolveInfos = pm.queryIntentActivities(intent, 0)
        for (resolveInfo in resolveInfos) {
            if (resolveInfo.activityInfo != null) {
                am.killBackgroundProcesses(resolveInfo.activityInfo.packageName)
            }
        }
    }
}
